import { MODEL_NAME } from '../../constants/model-names';
import { EVENTS, type IEventBus } from '../../events';
import type { BaseSnapshot } from '../../systems/save';
import { BaseModel } from '../base';

export interface UserInfoV1 extends BaseSnapshot {
  version: 1;
  username: string;
  saveTag: string[];
}

export type UserInfoSnapshot = UserInfoV1;

export type UserInfoSnapshotOld = UserInfoV1;

export class UserInfoModel extends BaseModel {
  public name = MODEL_NAME.USER_INFO;
  private bus: IEventBus;
  private username = '';
  /** 存档印记 */
  private saveTag: string[] = [];

  constructor(bus: IEventBus) {
    super();
    this.bus = bus;
  }

  /** 设置用户名称 */
  public setUsername(username: string) {
    this.username = username;
    this.bus.emit(EVENTS.USER_INFO_STATE_UPDATE);
  }

  /** 获取用户名称 */
  public getUsername() {
    return this.username;
  }

  /** 添加印记 */
  public addSaveTag(saveTag: string) {
    this.saveTag.push(saveTag);
  }

  get uiState() {
    return {
      username: this.username,
      saveTag: this.saveTag,
    };
  }

  public override save(): UserInfoSnapshot {
    return {
      version: 1,
      username: this.username,
      saveTag: this.saveTag,
    };
  }

  public override load(snapshot: any): void {
    this.username = snapshot.username;
    this.saveTag = snapshot.saveTag;
  }
}
